from flask import jsonify, request, send_from_directory, render_template
import os
from datetime import datetime
from werkzeug.utils import secure_filename
from .config import Config

def init_routes(app):
    """初始化路由"""
    
    @app.route('/upload', methods=['POST'])
    def upload_video():
        if 'file' not in request.files:
            return jsonify({'error': 'No file part'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': 'No selected file'}), 400
        
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
            unique_filename = f"{timestamp}_{filename}"
            
            # 确保上传目录存在
            os.makedirs(Config.UPLOAD_FOLDER, exist_ok=True)
            input_path = os.path.join(Config.UPLOAD_FOLDER, unique_filename)
            file.save(input_path)
            
            # 启动处理任务
            from .tasks import process_video_task
            task = process_video_task.delay(unique_filename)
            
            return jsonify({
                'task_id': task.id,
                'filename': unique_filename
            }), 202
        
        return jsonify({'error': 'Invalid file type'}), 400
    
    @app.route('/status/<task_id>')
    def task_status(task_id):
        from .tasks import process_video_task
        task = process_video_task.AsyncResult(task_id)
        
        response = {
            'state': task.state,
            'status': 'Pending...',
            'progress': 0
        }
        
        if task.state == 'PROGRESS':
            response.update({
                'status': task.info.get('status', ''),
                'progress': task.info.get('progress', 0)
            })
        elif task.state == 'SUCCESS':
            response.update({
                'status': task.info.get('status', ''),
                'result': task.info.get('result', ''),
                'progress': 100
            })
        elif task.state == 'FAILURE':
            response.update({
                'status': str(task.info),
                'progress': 0
            })
        
        return jsonify(response)
    
    @app.route('/download/<filename>')
    def download_file(filename):
        # 确保处理目录存在
        os.makedirs(Config.PROCESSED_FOLDER, exist_ok=True)
        return send_from_directory(
            Config.PROCESSED_FOLDER,
            filename,
            as_attachment=True,
            mimetype='video/mp4'
        )
    
    @app.route('/')
    def index():
        #return send_from_directory('templates', 'index.html')
        return render_template('index.html')
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in Config.ALLOWED_EXTENSIONS
